#include <iostream>
#include <string>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <thread>
#include <cstring>

using namespace std;

#define PORT 8888
#define BUF_SIZE 1024

void receive_messages(int sockfd) {
    char buf[BUF_SIZE];
    while (true) {
        int len = recv(sockfd, buf, BUF_SIZE - 1, 0);
        if (len <= 0) break;
        buf[len] = '\0';
        cout << buf;
        cout.flush();
    }
}

int main() {
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0) {
        perror("socket");
        return 1;
    }

    sockaddr_in serv_addr {};
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(PORT);
    serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");

    if (connect(sockfd, (sockaddr*)&serv_addr, sizeof(serv_addr)) < 0) {
        perror("connect");
        return 1;
    }

    string name;
    cout << "Enter your nickname: ";
    getline(cin, name);
    send(sockfd, name.c_str(), name.size(), 0);

    thread t(receive_messages, sockfd);

    string msg;
    while (getline(cin, msg)) {
        msg += "\n";
        send(sockfd, msg.c_str(), msg.size(), 0);
        if (msg == "/quit\n") break;
    }

    close(sockfd);
    t.detach();
    return 0;
}

